package com.cskaoyan.mall.product.service.impl;


import com.cskaoyan.mall.product.converter.dto.TestConverter;
import com.cskaoyan.mall.product.dto.TestDTO;
import com.cskaoyan.mall.product.mapper.SkuInfoMapper;
import com.cskaoyan.mall.product.model.SkuInfo;
import com.cskaoyan.mall.product.service.TestService;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    SkuInfoMapper skuInfoMapper;
    @Autowired
    TestConverter converter;
    @Autowired
    RedissonClient redissonClient;


    @Override
    public TestDTO getProductById(Long id) {

        SkuInfo skuInfo = skuInfoMapper.selectById(id);
        return converter.skuInfoPO2DTO(skuInfo);
    }

    @Override
    public synchronized void incrWithLock() {
        // 我们自己实现的分布式锁
        // myLock();

        // 基于Redisson实现的分布式锁
        // 1. 获取锁
        Lock lockObj = redissonClient.getLock("number:lock");
        // 2. 加锁
            // 如果成功，继续往下执行；
            // 如果失败，阻塞等待
        lockObj.lock();
        try {
            // 3. 共享数据的访问
            RBucket<Integer> bucket = redissonClient.getBucket("number");
            // 获取key为number的value值
            int number = bucket.get();
            // 自增1
            number++;
            // 在放回redis
            bucket.set(number);
        }finally {
            // 4. 释放锁
            lockObj.unlock();
        }

    }

    private void myLock() {
        String uuId = UUID.randomUUID().toString();

        // 1. 加分布式锁  key：number:lock  value：任意
        RBucket<String> lockBucket = redissonClient.getBucket("number:lock");
        // 1.1 尝试加锁 trySet底层用的是setnx命令
        boolean success = lockBucket.trySet(uuId,5, TimeUnit.SECONDS);
        while (!success) {
            // 1.2 等待50秒
            try {
                TimeUnit.SECONDS.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            success = lockBucket.trySet("lockObj");
        }

        // 2. 共享数据的访问
        try{
            RBucket<Integer> bucket = redissonClient.getBucket("number");
            // 获取key为number的value值
            int number = bucket.get();
            // 自增1
            number++;
            // 在放回redis
            bucket.set(number);
        }finally {
            // 3. 释放锁（本质是删除）
            // 获取成功的线程在加锁时添加的uuid，与redis中的uuid对比，如果一致，则删除锁
            String Flag = lockBucket.get();
            if (Flag.equals(uuId)){
                lockBucket.delete();
            }
        }
    }
}
